<template>
  <div class="player" v-show="this.playlist.length>0">
    <transition name="normal"
                @enter="enter"
                @after-enter="afterEnter"
                @leave="leave"
                @after-leave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img width="100%" height="100%" :src="currentSong.pic">
        </div>
        <div class="top">
          <div class="back" @click="back">
            <i class="icon-back"></i>
          </div>

          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
        </div>
        <div class="middle"
             @touchstart.prevent="middleTouchStart"
             @touchmove.prevent="middleTouchMove"
             @touchend="middleTouchEnd"
        >
          <div class="middle-l " ref="middleL">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" ref="imageWrapper">
                <img ref="image" :class="cdCls" class="image" :src="currentSong.pic">
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{ playingLyric }}</div>
            </div>
          </div>
          <!-- 中间歌词的滑动            -->
          <scroll class="middle-r" ref="lyricList">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p ref="lyricLine"
                   class="text"
                   v-for="(line,index) in currentLyric.lines"
                   :key="index"
                >
                  {{ line.txt }}
                </p>
              </div>
            </div>
          </scroll>
        </div>
        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot" :class="{'active': currentShow==='cd'}"></span>
            <span class="dot" :class="{'active': currentShow==='lyric'}"></span>
          </div>
          <div class="progress-wrapper">
            <span class="time time-l">{{format(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar ref="progressBar" :percent="percent" @percentChange="onProgressBarChange"
                            @percentChanging="onProgressBarChanging"></progress-bar>
            </div>
            <span class="time time-r">{{format(currentSong.duration)}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left" @click="changeMode">
              <i :class="iconMode" ></i>
            </div>

            <div class="icon i-left" :class="disableCls">
              <i @click="prev" class="icon-prev"></i>
            </div>

            <div class="icon i-center" :class="disableCls">
              <i class="needsclick" @click="togglePlaying" :class="playIcon"></i>
            </div>
            <div class="icon i-right" :class="disableCls">
              <i @click="next" class="icon-next"></i>
            </div>
            <div class="icon i-right">
              <i @click="toggleFavorite(currentSong)" class="icon" :class="favoriteIcon"></i>
            </div>
          </div>
        </div>
      </div>

    </transition>

    <transition name="mini">
      <div class="mini-player"></div>
    </transition>
    <audio ref="audio" @playing="ready" @error="error" @timeupdate="updateTime"
           @ended="end" @pause="paused"></audio>
  </div>

</template>

<script>
import {mapGetters, mapMutations, mapActions} from 'vuex'
import {playerMixin} from 'common/js/mixin'
import {getLyric} from 'api/song'
import Lyric from 'lyric-parser'
import Scroll from 'base/scroll/scroll'
import { prefixStyle } from 'common/js/dom'
const transform = prefixStyle('transform')
const transitionDuration = prefixStyle('transitionDuration')
import ProgressBar from 'base/progress-bar/progress-bar'
import { playMode } from 'common/js/config'
export default {
  name: "player",
  mixins: [playerMixin],
  data() {
    return {
      currentShow: 'cd',
      songReady: false,
      playingLyric: '',
      currentLyric: null,
      isPureMusic: false,
      currentTime: 0,
    }
  },

  created() {
    this.touch = {}
  },
  components: {
    Scroll,
    ProgressBar
  },
  methods: {

    ready(){

    },
    error(){},

    updateTime(e){
      //获取到当前时间
      this.currentTime = e.target.currentTime

    },
    end(){

    },
    paused(){

    },
    loop () {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
      this.setPlayingState(true)
      if (this.currentLyric) {
        this.currentLyric.seek(0)
      }
    },
    prev() {
      if (!this.songReady) {
          return;
      }
      if (this.playlist.length === 1) {
        this.loop()
      } else {
        let index = this.currentIndex - 1
        if (index === -1) {
          index = this.playlist.length - 1
        }
        this.setCurrentIndex(index)
        if (!this.playing) {
          this.togglePlaying()
        }
      }

    },
    next() {

      if (!this.songReady) {
        return
      }
      if (this.playlist.length === 1) {
        this.loop()
      } else {
        let index = this.currentIndex + 1
        if (index === this.playlist.length) {
          index = 0
        }
        this.setCurrentIndex(index)
        if (!this.playing) {
          this.togglePlaying()
        }
      }
    },
    togglePlaying() {
      if (!this.songReady) {
        return
      }
      this.setPlayingState(!this.playing)
      if (this.currentLyric) {
        this.currentLyric.togglePlay()
      }
    },

    changeMode() {
    },
    enter() {

    },
    afterEnter() {

    },
    leave() {

    },
    afterLeave() {

    },
    format (interval) {
      interval = interval | 0
      const minute = interval / 60 | 0
      const second = this._pad(interval % 60)
      return `${minute}:${second}`
    },
    _pad (num, n = 2) {
      let len = num.toString().length
      while (len < n) {
        num = '0' + num
        len++
      }
      return num
    },


    onProgressBarChanging (percent) {
      this.currentTime = this.currentSong.duration * percent
      if (this.currentLyric) {
        this.currentLyric.seek(this.currentTime * 1000)
      }
    },
    onProgressBarChange(percent){
      const currentTime = this.currentSong.duration * percent
      this.currentTime = this.$refs.audio.currentTime = currentTime
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
      if (!this.playing) {
        this.togglePlaying()
      }

    },
    back() {
      this.setFullScreen(false)
    },

    middleTouchStart(e) {
      this.touch.initiated = true
      this.touch.directionLocked = ''
      //用来判断是否是一次移动
      this.touch.moved = false
      const touch = e.touches[0]
      this.touch.startX = touch.pageX
      this.touch.startY = touch.pageY
    },
  //这个滑动主要的目的是左右滑动
    middleTouchMove(e) {
      if (!this.touch.initiated) {
        return
      }

      const touch = e.touches[0]
      const deltaX = touch.pageX - this.touch.startX
      const deltaY = touch.pageY - this.touch.startY


      const absDeltaX = Math.abs(deltaX)
      const absDeltaY = Math.abs(deltaY)
      if (!this.touch.directionLocked) {
        if (absDeltaX > absDeltaY) {
          this.touch.directionLocked = 'h' // lock horizontally
        } else if (absDeltaY >= absDeltaX) {
          this.touch.directionLocked = 'v' // lock vertically
        }
      }

      if (this.touch.directionLocked === 'v') {
        return
      }

      if (!this.touch.moved) {
        this.touch.moved = true
      }

      const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
      const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      //在播放的时候可能是有百分比
      this.touch.percent = Math.abs(offsetWidth / window.innerWidth)


      this.$refs.lyricList.$el.style[transitionDuration] = 0
      this.$refs.middleL.style.opacity = 1 - this.touch.percent
      this.$refs.middleL.style[transitionDuration] = 0
    },

    middleTouchEnd () {
      if (!this.touch.moved) {
        return
      }
      let offsetWidth
      let opacity
      if (this.currentShow === 'cd') {
        if (this.touch.percent > 0.1) {
          offsetWidth = -window.innerWidth
          opacity = 0
          this.currentShow = 'lyric'
        } else {
          offsetWidth = 0
          opacity = 1
        }
      } else {
        if (this.touch.percent < 0.9) {
          offsetWidth = 0
          this.currentShow = 'cd'
          opacity = 1
        } else {
          offsetWidth = -window.innerWidth
          opacity = 0
        }
      }
      const time = 300
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`
      this.$refs.middleL.style.opacity = opacity
      this.$refs.middleL.style[transitionDuration] = `${time}ms`
      this.touch.initiated = false
    },

    handleLyric({lineNum, txt}) {
      this.playingLyric = txt

    },
    getLyrics() {
      getLyric(this.currentSong).then((lyric) => {
        this.currentLyric = new Lyric(lyric, this.handleLyric)
        this.currentLyric.lines.length;
        this.isPureMusic = !this.currentLyric.lines.length
        if (this.isPureMusic) {

        } else {
          if (this.playing) {
            // 这个时候有可能用户已经播放了歌曲，要切到对应位置
            this.currentLyric.seek(this.currentTime * 1000)
          }
        }

        //这一页只显示当前歌词

      }, (error => {

      }))
    },
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN'
    }),


  },
  watch: {
    currentSong(newSong, oldSong) {

      if (!newSong.id || !newSong.url || newSong.id === oldSong.id) {
        return
      }
      if (this.currentLyric) {
        this.currentLyric.stop()
        // 重置为null
        this.currentLyric = null
        this.currentTime = 0
        this.playingLyric = ''
        this.currentLineNum = 0
      }
      this.$refs.audio.src = newSong.url
      this.$refs.audio.play()

      // 若歌曲 5s 未播放，则认为超时，修改状态确保可以切换歌曲。
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.songReady = true
      }, 5000)
      //获取歌词
      this.getLyrics()
    },
    playing (newPlaying) {
      if (!this.songReady) {
        return
      }
      const audio = this.$refs.audio
      this.$nextTick(() => {
        newPlaying ? audio.play() : audio.pause()
      })
      if (!newPlaying) {
        if (this.fullScreen) {
         // this.syncWrapperTransform('imageWrapper', 'image')
        } else {
         //this.syncWrapperTransform('miniWrapper', 'miniImage')
        }
      }
    },
  },
  computed: {
    ...mapGetters([
      'currentIndex',
      'fullScreen',
      'playing'
    ]),
    cdCls() {
      return this.playing ? 'play' : ''
    },
    disableCls() {
      return this.songReady ? '' : 'disable'
    },
    playIcon() {
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    percent () {
      return this.currentTime / this.currentSong.duration
    },
    iconMode (){
      if (this.mode === playMode.sequence){
        return 'icon-sequence'
      }else if(this.mode === playMode.loop){
        return 'icon-loop'
      }else{
        return 'icon-random'
      }
    }
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
@import "~common/stylus/variable"
@import "~common/stylus/mixin"
.player
  .normal-player
    position: fixed
    left: 0
    right: 0
    top: 0
    bottom: 0
    z-index: 150
    background: $color-background

    .background
      position absolute
      left 0
      top 0
      width 100%
      height 100%
      opacity: 0.6
      filter: blur(20px)

    .top
      position relative
      margin-bottom 20px

      .back
        position absolute
        top 0
        left 6px
        z-index: 50

        .icon-back
          display: block
          padding: 9px
          font-size: $font-size-large-x
          color: $color-theme
          transform: rotate(-90deg)

      .title
        width: 70%
        margin: 0 auto
        line-height: 40px
        text-align: center
        no-wrap()
        font-size: $font-size-large
        color: $color-text

      .subtitle
        line-height: 20px
        text-align: center
        font-size: $font-size-medium
        color: $color-text

    .middle
      position fixed
      width: 100%
      top: 80px
      bottom: 170px
      white-space: nowrap
      font-size: 0

      .middle-l
        display inline-block
        position: relative
        width 100%
        height 0
        padding-top 80%

        .cd-wrapper
          position absolute
          top 0
          left 10%
          width 80%
          box-sizing: border-box
          height: 100%
          .cd
            width: 100%
            height: 100%
            border-radius: 50%
            .image
              position: absolute
              left: 0
              top: 0
              width: 100%
              height: 100%
              box-sizing: border-box
              border-radius: 50%
              border: 10px solid rgba(255, 255, 255, 0.1)
            .play
              animation: rotate 20s linear infinite

        .playing-lyric-wrapper
          margin 30px auto 0 auto
          width 80%
          overflow: hidden
          text-align: center

          .playing-lyric
            height: 20px
            line-height: 20px
            font-size: $font-size-medium
            color: $color-text-l

      .middle-r
        display: inline-block
        vertical-align: top
        width: 100%
        height: 100%
        overflow: hidden
        .lyric-wrapper
          width: 80%
          margin: 0 auto
          overflow: hidden
          text-align: center
          .text
            line-height: 32px
            color: $color-text-l
            font-size: $font-size-medium
            &.current
              color: $color-text
    .bottom
      position: absolute
      bottom: 50px
      width: 100%
      .dot-wrapper
        text-align: center
        font-size: 0
        .dot
          display: inline-block
          vertical-align: middle
          margin: 0 4px
          width: 8px
          height: 8px
          border-radius: 50%
          background: $color-text-l
          &.active
            width: 20px
            border-radius: 5px
            background: $color-text-ll
      .progress-wrapper
        display flex
        width 80%
        margin 0 auto
        .progress-bar-wrapper
          flex 1
        .time
          color: #fff;
          font-size: 12px;
          flex: 0 0 40px;
          line-height: 30px;
        &.time-l
          text-align left
        &.time-r
          text-align right
      .operators
        display: flex
        align-items: center
        .icon
          flex: 1
          color: $color-theme
          &.disable
            color: $color-theme-d
          i
            font-size: 30px
        .i-left
          text-align: right
        .i-center
          padding: 0 20px
          text-align: center
          i
            font-size: 40px
        .i-right
          text-align: left
        .icon-favorite
          color: $color-sub-theme

</style>
